import React from 'react'
import NavbarCom from '../components/NavbarCom'
import { Tabs, InfiniteScroll } from 'antd-mobile'
import { getNewsCategoryApi, getNewsListApi } from '../service/newService'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'

export default function News() {

  const [newscate, setnewscate] = useState([])
  const [newsList, setnewsList] = useState([])
  const [pages, setpages] = useState({ pageNum: 1, pageSize: 10 })

  let getNewsData = async () => {
    let res = await getNewsCategoryApi({})
    // console.log(res);

    setnewscate(res.data.data)
    let res2 = await getNewsListApi({ pageNum: pages.pageNum, pageSize: pages.pageSize })
    // console.log(res2);
    setnewsList(res2.data.rows)

  }


  useEffect(() => {
    getNewsData()
  }, [])


  let changeCate = async (id: string) => {
    if (id) {
      let res = await getNewsListApi({ type: id })
      setnewsList(res.data.rows)
      setHasMore(false)
    } else {
      setHasMore(true)
      setpages({ pageNum: 1, pageSize: 10 })
      let res = await getNewsListApi({ pageNum: pages.pageNum, pageSize: pages.pageSize })
      setnewsList(res.data.rows)
    }
  }

  const [hasMore, setHasMore] = useState(true)
  async function loadMore() {
    setpages({ pageNum: pages.pageNum + 1, pageSize: 10 })
    let res = await getNewsListApi({ pageNum: pages.pageNum, pageSize: pages.pageSize })
    let List = newsList.concat(res.data.rows)
    setnewsList(List)
    if (pages.pageNum > 5) {
      setHasMore(false)
    }
  }
  let navigate = useNavigate();
  let goto = (item: any) => {
    navigate('/news/detail', { state: { id: item.id } })
    console.log(item);
  }
  return (
    <div className='news-all'>
      <NavbarCom children={"新闻咨询"} backArrow={false}></NavbarCom>
      <div className='div-h'></div>
      {/* 导航栏 */}
      <Tabs defaultActiveKey='' style={{ '--title-font-size': '14px' }} onChange={changeCate}>
        <Tabs.Tab title='全部' key='' >
        </Tabs.Tab>
        {
          newscate.map((item: any) => {
            return <Tabs.Tab title={item.name} key={item.id}  >
            </Tabs.Tab>
          })
        }
      </Tabs>

      {/* 列表 */}
      <ul>
        {
          newsList.map((item: any, index) => {
            return <li key={index} onClick={() => { goto(item) }}>
              <img src={"/api2/" + item.cover} alt="" />
              <div className='new-txt'>
                <h3>{item.title}</h3>
                <p dangerouslySetInnerHTML={{ __html: item.content.replace(/<img[^>]*src[=\"\'\s]+[^\.]*\/([^\.]+)\.[^\"\']+[\"\']?[^>]*>/gi, "") }}></p>
                <div className='new-bom'> <span className='span1'>评论总数:{item.commentNum}</span> <span>发布时间:{item.publishDate}</span></div>
              </div>
            </li>
          })
        }
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </ul>

    </div >
  )
}
